<!-- 合同管理 -->
<template>
  <div class="app-container ">
    <div class="">
      <el-form ref="queryForm" :inline="true" class=" search-form-new" label-width="68px">
        <el-form-item label="店铺" prop="tenantId" v-hasPermi="['searchTenantID']">
          <el-select v-model="queryParams.tenantId" placeholder="请选择店铺" clearable filterable>
            <el-option v-for="dict in tenantList" :key="dict.tenantId" :label="dict.tenantName" :value="dict.tenantId" />
          </el-select>
        </el-form-item>
        <el-form-item label="合同编号" prop="contractNo">
          <el-input v-model="queryParams.contractNo" placeholder="请输入合同编号" clearable size="small" />
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable size="small" />
        </el-form-item>
        <el-form-item label="创建人" prop="createName">
          <el-input v-model="queryParams.createName" placeholder="请输入创建人昵称" clearable size="small" />
        </el-form-item>
        <el-form-item label="合同类型" prop="bussinessType">
          <el-select v-model="queryParams.bussinessType" placeholder="请选择" clearable size="small">
            <el-option v-for="(item,key) in commonMaps.hetongTypeMap" :key="key" :label="item.name" :value="key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="合同状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable size="small">
            <el-option v-for="(item,key) in commonMaps.hetongStatusMap" :key="key" :label="item.name" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker clearable v-model="timerange" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="完成时间">
          <el-date-picker clearable v-model="timerange2" size="small" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item class="btns">
          <el-button type="primary" icon="el-icon-search" @click="searchFn">搜索</el-button>
          <el-button type="warning" icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          <el-button v-if="checkPermi(['chuangjianhetong'])" icon="el-icon-plus" type="primary" size="mini" @click="addACount" class="zdy-btn zdy-btn-refresh">创建合同</el-button>

        </el-form-item>
      </el-form>
      <div class="tip">合同创建后，请在{{ hetongguoqiDays }}天内完成签署，超时将自动撤销合同！</div>
      <div class="table_box table_box_new" v-loading="loading">
        <el-table :data="tableData.records" border>
          <el-table-column label="商户名称" prop="tenantName" show-overflow-tooltip/>
          <el-table-column label="合同编号" prop="contractNo" width="160"/>
          <el-table-column label="合同类型" prop="bussinessType" width="100">
            <template slot-scope="scope">
              <div>
                <el-tag :type="commonMaps.hetongTypeMap[scope.row.bussinessType||0].type">{{ commonMaps.hetongTypeMap[scope.row.bussinessType||0].name }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="合同名称" prop="contractName"> </el-table-column>
          <el-table-column label="创建时间" prop="createTime" width="160"> </el-table-column>
          <el-table-column label="创建人" prop="createName" > </el-table-column>

          <el-table-column label="状态" prop="status" width="100">
            <template slot-scope="scope">
              <div>
                <el-tag :type="commonMaps.hetongStatusMap[scope.row.status||1].type">{{ commonMaps.hetongStatusMap[scope.row.status||1].name }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="签署人" prop="">
            <template slot-scope="scope">
              <div v-if="scope.row.signUser">
                <div class="qianshuren" v-for="(item,i) in JSON.parse(scope.row.signUser)" :key="i">
                  <span>签署人{{ i+1 }}:</span>
                  <span>{{ item.companyName||item.name }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="签署完成时间" prop="finishTime" width="160"/>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button v-if="scope.row.status==2" type="text" @click="downloadFile(scope.row)">下载合同</el-button>
              <el-button type="text" @click="openView(scope.row)">签署详情</el-button>
              <el-button v-if="scope.row.status==1&&checkPermi(['chexiaohetong'])" type="del" @click="cancelContract(scope.row)">撤销合同</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="pages-box">
        <pagination v-show="tableData.total>0" :total="tableData.total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

      </div>

    </div>

    <CreateContract ref="CreateContract"></CreateContract>
    <viewContract ref="viewContract"></viewContract>
  </div>
</template>

<script>
import fadadaApi from "../../api/B2Cmanage/fadada";
import CreateContract from "./createContract.vue";
import { getToken } from "@/utils/auth";
import viewContract from "./viewContract.vue";
export default {
  name: "AiqianContractList",
  components: { CreateContract, viewContract },
  data() {
    return {
      importheaders: {
        Authorization: "Bearer " + getToken(),
        timeout: 1000 * 60 * 10,
      },
      timerange: [],
      timerange2: [],
      // shangchuan: {
      //   url: "https://imgage.maimaihao.com/%E7%88%B1%E7%AD%BE%E6%B5%8B%E8%AF%95.docx",
      //   fileName: "ceshi",
      //   extension: "docx",
      //   file: "",
      // },
      // yanzhengma: "",
      // serialNo: "PA10120250415105446630871",
      tableData: {
        records: [],
        total: 0,
      },
      queryParams: {
        pageSize: 10,
        pageNum: 1,
        tenantId:''
      },

      loading: false,
      hetongguoqiDays: 15,
    };
  },
  computed: {
    tenantList() {
      return this.$store.getters.tenantList;
    },
  },
  created() {
    this.getList();
    this.getGuoqiDays();
    // this.getTypeList();
  },

  activated() {
    // this.getList();
  },
  methods: {
    // 获取列表
    getList() {
      this.tableData.records = [];
      this.loading = true;
      let obj = this.queryParams;
      if (this.timerange.length == 2) {
        obj.createTimeStart = this.timerange[0] + " 00:00:00";
        obj.createTimeEnd = this.timerange[1] + " 23:59:59";
      } else {
        obj.createTimeStart = "";
        obj.createTimeEnd = "";
      }
      if (this.timerange2.length == 2) {
        obj.finishTimeStart = this.timerange2[0] + " 00:00:00";
        obj.finishTimeEnd = this.timerange2[1] + " 23:59:59";
      } else {
        obj.finishTimeStart = "";
        obj.finishTimeEnd = "";
      }
      fadadaApi
        .contracthistory(obj)
        .then((response) => {
          // console.log("%c Line:111 🥑 response", "color:#42b983", response);
          this.$nextTick(() => {
            this.loading = false;
            this.tableData.records = response.rows;
            this.tableData.total = response.total;
          });
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    // 获取合同过期天数
    getGuoqiDays() {
      this.getDicts("aiQianConfig").then((r) => {
        if (r.data && r.data.length) {
          const lianxiObj = this.arrayToObject(r.data, "dictLabel");
          if (lianxiObj.validityTime) {
            // this.hetongguoqiDays = lianxiObj.validityTime.remark
            this.hetongguoqiDays = 15;
          }
        }
      });
    },
    // 搜索
    searchFn() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置
    resetQuery() {
      this.queryParams = {
        pageSize: 10,
        pageNum: 1,
      };
      this.timerange2 = [];
      this.timerange = [];
      this.searchFn();
    },

    // 新增
    addACount() {
      this.$refs.CreateContract.open();
    },
    getUserTest() {
      fadadaApi
        .getuser({
          account: "yyenterprise13785552222",
          type: 2,
        })
        .then((res) => {});
    },
    //
    // shiming() {
    //   fadadaApi.testMobile3().then((res) => {
    //     if (res.msg) {
    //       const obj = JSON.parse(res.msg);
    //       this.serialNo = obj.serialNo;
    //     }
    //   });
    // },
    // jiaoyan() {
    //   fadadaApi
    //     .contractxiaoyan({
    //       captcha: this.yanzhengma,
    //       serialNo: this.serialNo,
    //     })
    //     .then((res) => {
    //       console.log("%c Line:122 🍔 res", "color:#f5ce50", res);
    //     });
    // },
    // 查看签署链接
    openView(row) {
      this.$refs.viewContract.open(row.id);
    },
    // 撤销合同
    cancelContract(row) {
      this.$confirm("合同撤销后不能继续签署，确定撤销该合同吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;

          // const authPhone= this.tabIndex==2?this.ruleForm.phone:this.ruleForm2.phone
          fadadaApi
            .contractcancel({
              id: row.id,
            })
            .then((res) => {
              if (res.code == 200) {
                this.$message.success("合同撤销成功！");
              }
              this.getList();
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },
    isValidBase64(str) {
      // 使用正则表达式检查基本格式，并确保长度是4的倍数或可以通过填充补齐
      return (
        /^[A-Za-z0-9+/=]+$/.test(str) &&
        (str.length % 4 === 0 || str.match(/=+$/) !== null)
      );
    },
    // 查看
    downloadFile(row) {
      // 查看详情
      fadadaApi
        .getcontractIFile({
          id: row.id,
        })
        .then((res) => {
          const fileData = JSON.parse(res.msg);
          const base64Data = fileData.data.data;
          let mimeType = "application/pdf"; // 根据需要更改 MIME 类型
          if (fileData.data.fileType !== 0) {
            mimeType = "application/zip";
          }
          let fileType = ".pdf";
          if (fileData.data.fileType !== 0) {
            fileType = ".zip";
          }
          // 将 Base64 转换为二进制数据
          const byteCharacters = atob(base64Data);
          const byteNumbers = new Array(byteCharacters.length);
          for (let i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
          }
          const byteArray = new Uint8Array(byteNumbers);

          // 创建 Blob 对象
          const blob = new Blob([byteArray], { type: mimeType });

          // 创建下载链接
          const link = document.createElement("a");
          link.href = window.URL.createObjectURL(blob);
          link.download = row.contractName + fileType; // 下载的文件名

          // 触发下载
          link.click();

          // 释放 URL 对象
          window.URL.revokeObjectURL(link.href);
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.model-cont-item {
  border-bottom: 1px solid #ccc;
}
.tip {
  color: #ff4b4b;
  margin-bottom: 10px;
}
.qianshuren{
  text-align: left;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  width: 100%;
}
</style>
